﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using PessMvc.Models;
using PessModel;
using System.Text.RegularExpressions;
using System.Web.Mvc.Html;

namespace PessMvc.Helpers
{
    public static class Extensions
    {
        public static string FileExtName(this string fileName)
        {
            int lastIdx=fileName.LastIndexOf('.');
            return fileName.Substring(lastIdx+1, fileName.Length - lastIdx-1);
        }
        public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper,
                                            string linkText, string actionName, string controllerName,object routeValues)
        {

            string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

            if (controllerName == currentController||                
                currentController.RelatedControllers().Contains(controllerName))
            {
                return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, new { @class = "selected" });
            }

            return htmlHelper.ActionLink(linkText, actionName, controllerName,routeValues,null);


        }
        private static List<string> RelatedControllers(this string currentController)
        {
            List<string> controllers=new List<string>();
            switch (currentController)
            {
                case "ExpertGroup": case "ExpertJudge":
                    controllers=new List<string> { "ExpertGroup", "ExpertJudge" };
                    break;
                case "Rule":case "Subject":
                    controllers = new List<string> { "Rule", "Subject" };
                    break;
            }
            return controllers;

        }
        public static MvcHtmlString PivotTable(this HtmlHelper helper, DataTable datatable, string xAxisField, string yAxisField, string[] zAxisFields)
        {
            Pivot pivot = new Pivot(datatable);

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            pivot.PivotTable(xAxisField, yAxisField, zAxisFields).RenderControl(htw);
            return MvcHtmlString.Create(sb.ToString());
        }
        //public static MvcHtmlString RichTextareaFor(this HtmlHelper helper, string id, string text = "")
        //{
        //    //return new MvcHtmlString(String.Format(@"<textarea id="{0}" class="tinymce">{1}</textarea>",id,text));
        //    return new MvcHtmlString(String.Format(@"<textarea id=""{0}"" class=""tinymce"">{1}</textarea>", id, text));
        //}

        public static List<ExpertJudgeModel> ToExpertJudgeModelList(this IList<ExpertJudge> experts)
        {
            var expertModels = new List<ExpertJudgeModel>();
            foreach (var e in experts)
            {
                var model = new ExpertJudgeModel
                {
                    RealName = e.RealName,
                    Birthdate = e.BirthDate,
                    Gender = e.Gender,
                    Phone = e.Phone,
                    SerialNumber = e.SerialNumber,
                    ExpertGroupID = e.ExpertGroupID//,
                    //ExpertGroupCallsign=e.ExpertGroups.SelectMany(e.ExpertGroups)
                    //ExpertGroupCallsign = e.ExpertGroup.Callsign 
                };
                foreach (var group in e.ExpertGroups)
                {
                    model.ExpertGroupCallsign += group.Callsign + " ";
                }
                expertModels.Add(model);
            }
            return expertModels;
        }

        public static IHtmlString PhotoImage(this HtmlHelper htmlHelper, string url)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            var img = new TagBuilder("img");
            img.Attributes["alt"] = "[IMAGE]";
            img.Attributes["src"] = urlHelper.Content(url);
            return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
        }

        public static string ToLocalName(this ActivityStatus status)
        {
            string value="";
            switch (status)
            {
                case ActivityStatus.Open:
                    value = PessResources.ActivityStatus.Open;
                    break;
                case ActivityStatus.Close:
                    value = PessResources.ActivityStatus.Close;
                    break;
                case ActivityStatus.Done:
                    value = PessResources.ActivityStatus.Done;
                    break;
            }
            return value;
        }

        public static string StripHtmlTags(this string post)
        {
            if (post == null)
            {
                return "";
            }
            else
            {
                return Regex.Replace(post, @"<[^>]*>", String.Empty);
            }
        }
        public static string Truncate(this string input, int length)
        {
            if (input==null||input.Length <= length)
            {
                return input;
            }
            else
            {
                return input.Substring(0, length) + "...";
            }
        }
    }
    public static class PagingHelpers
    {
        ///  <summary>
        /// This method returns an MVCHtmlString which
        /// is used for Paging purpose. this represents
        /// that it is an extension method, PageInfo is a
        /// ViewModel class which I had created and pageUrl
        /// is anomyous type function.
        ///  </summary>
        public static MvcHtmlString PageLinks(this HtmlHelper html, PageInfo pageInfo, Func<int, string> pageUrl)
        {
            //Create an object of StringBuilder class
            StringBuilder result = new StringBuilder();

            for (int i = 1; i <= pageInfo.TotalPages; i++)
            {
                //TagBuilder class is used to create Tag.
                //Here I am creating <a></a> tag.
                TagBuilder tag = new TagBuilder("a");
                //Merge required attributed like href, title etc.
                tag.MergeAttribute("href", pageUrl(i));
                //Set inner heml.
                tag.InnerHtml = i.ToString();

                if (i == pageInfo.CurrentPage)
                {
                    //Add any class if you want to add.
                    tag.AddCssClass("selected");
                }
                //Finally add resulted string in StringBuilder object.
                result.Append(tag.ToString());
            }

            //Create MVCHtmlString.
            return MvcHtmlString.Create(result.ToString());
        }
    }
}